package org.correct.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.correct.config.Config;
import org.correct.correcter.Correcter;
import org.correct.correcter.ResultNode;
import org.correct.model.PageItem;
import org.correct.search.Search;

public class SearchServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException { 
		System.out.println("In SearchServlet...");
		String keyword = request.getParameter("wd");
		String url = request.getParameter("url");
		if(url != null) {
			response.sendRedirect(url);
			Initializer.logger.log(keyword, url);
			return;
		}

		int pn = 0;
		String pnStr = request.getParameter("pn");
		if(pnStr != null) {
			try {
				pn = Integer.parseInt(pnStr);
			} catch(NumberFormatException e) {
				pn = 0;
				e.printStackTrace();
			}
		}
		
		ResultNode rNode = null;
		Object[] result = null;
		PageItem[] plist = null;
		int ntotal = 0;
		
		try {
			rNode = Correcter.getSearchList(keyword);
			
			result = new Search(rNode.result).query(pn / Config.ITEM_NUM_PER_PAGE + 1);
			plist = (PageItem[])result[1];
			
			ntotal = (Integer)result[0];
			if(pn >= ntotal)
				pn = (ntotal > 0 ? ntotal - 1 : 0);
			
		} catch (Exception e) {
			e.printStackTrace();
			
			RequestDispatcher dispatcher = 
				request.getRequestDispatcher("error.jsp");
			dispatcher.forward(request, response);
			return;
		}
		/*
		List<PageItem> totalList = (List<PageItem>)result[1];
		
		if(totalList == null || totalList.size() == 0) {
			RequestDispatcher dispatcher = 
				request.getRequestDispatcher("error.jsp");
			dispatcher.forward(request, response);
			return;
		}
		
		if(pn > totalList.size())
			pn = (totalList.size() > 0 ? totalList.size() - 1 : 0);
		
		int indexLast = (pn + Config.ITEM_NUM_PER_PAGE > totalList.size() ?
				totalList.size() : pn + Config.ITEM_NUM_PER_PAGE);
		
		PageItem[] plist = totalList.subList(pn, indexLast).toArray(new PageItem[0]);
		*/
		
		request.setAttribute("keyword", keyword);
		request.setAttribute("plist", plist);
		request.setAttribute("pn", pn);
		request.setAttribute("nTotal", ntotal);
		request.setAttribute("correctAndTerms", rNode);
		
		RequestDispatcher dispatcher = 
			request.getRequestDispatcher("search.jsp");
		dispatcher.forward(request, response);
		
		// String keyword = (Strin)request.getAttribute("keyword");
		// PageItem[] plist = (PageItem[])request.getAttribute("plist");
		// String[] kwlist = (String[])request.getAttribute("kwlist");
		// int npstart = (Integer)request.getAttribute("pn");
		// int nptotal = (Integer)request.getAttribute("nTotal");
	}
}
